package website.lucaswork.survey.mvc.controllers;

import org.apache.log4j.Logger;
import org.apache.log4j.Priority;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import website.lucaswork.survey.core.dtos.SurveySummaryDTO;
import website.lucaswork.survey.core.services.SurveyService;
import website.lucaswork.survey.core.utils.DefaultValues;
import website.lucaswork.survey.mvc.forms.CreateSurveyForm;
import website.lucaswork.survey.mvc.utils.ConvertUtil;

import javax.validation.Valid;

@Controller
@RequestMapping("/survey")
public class SurveyController extends SurveyWCI {

    private final Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    ConvertUtil convertUtil;

    @Autowired
    SurveyService surveyService;

    @Autowired
    DefaultValues defaultValues;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String getSurveyList(Pageable pageable, Model model) {
        Page<SurveySummaryDTO> surveys = surveyService.getPageSurveys(pageable);
        model.addAttribute("surveys", surveys);
        return "/survey/list";
    }

    @ModelAttribute("datetimeFormat")
    public String getDatetimeFormat() {
        return defaultValues.getDefaultDatetimeFormatForJs();
    }

    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String createEntry(CreateSurveyForm createSurveyForm) {
        return "/survey/create";
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public String createProcessing(@Valid CreateSurveyForm createSurveyForm, BindingResult result, RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            return "/survey/create";
        }
        try {
            surveyService.saveSurvey(convertUtil.toSurveyValue(createSurveyForm));
            redirectAttributes.addFlashAttribute("message", "New survey created successfully");
            return "redirect:/survey/list";
        } catch (Exception e) {
            logger.error("error saving survey", e);
            result.addError(new ObjectError("createSurveyForm", "New survey created failed. Please contact the admin"));
            return "/survey/create";
        }
    }
}
